package com.yeswater.multithread.chapter7;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * author : yeswater
 * date : 2023/11/6
 * <p>
 * SimpleDateFormat 非线程安全
 *  2. ThreadLocal
 */

public class Run_7_6_3 {
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String[] dateStrArr = new String[]{"2000-01-01", "2000-01-02", "2000-01-03", "2000-01-04", "2000-01-05", "2000-01-06", "2000-01-07", "2000-01-08", "2000-01-09", "2000-01-10"};

        Thread1[] threadArr = new Thread1[10];
        for (int i = 0; i < 10; i++) {
            threadArr[i] = new Thread1(sdf, dateStrArr[i]);
        }

        for (int i = 0; i < 10; i++) {
            threadArr[i].start();
        }
    }

    private static class Thread1 extends Thread {
        private SimpleDateFormat sdf;
        private String date;

        public Thread1(SimpleDateFormat sdf, String date) {
            super();
            this.sdf = sdf;
            this.date = date;
        }

        @Override
        public void run() {
            try {
                System.out.println(DateTools.getSimpleDateFormat("yyyy-MM-dd").hashCode());
                Date dateRef = DateTools.getSimpleDateFormat("yyyy-MM-dd").parse(date);
                String newDate = DateTools.getSimpleDateFormat("yyyy-MM-dd").format(dateRef);
                if (!newDate.equals(date)) {
                    System.out.println("ThreadName=" + this.getName() + " 报错了 日期字符串:" + date + " 转换成的日期为: " + newDate);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private static class DateTools {
        private static  ThreadLocal<SimpleDateFormat> tl = new ThreadLocal<>();

        public static SimpleDateFormat getSimpleDateFormat(String datePattern) {
            SimpleDateFormat sdf = null;
            sdf = tl.get();
            if (sdf == null) {
                sdf = new SimpleDateFormat(datePattern);
                tl.set(sdf);
            }
            return sdf;
        }
    }
}
